import logging

from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings


class ExceptionMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception):
        logger_error = logging.getLogger('django_ERROR')
        request_body = request.body
        request_url = request.get_raw_uri()
        request_method = request.method
        error_msg = '\nRequest Body:{},\nRequest Url:{},\nRequest Method:{},\n{}'.format(request_body, request_url,
                                                                                         request_method, exception)
        json_resp = {'code': 500}

        if settings.DEBUG:
            json_resp['msg'] = str(exception)

        logger_error.error(error_msg)
        return JsonResponse(json_resp, status=200, safe=False)
